package com.example.java_chatroom_redis_rabbitmq.controller;

import com.example.java_chatroom_redis_rabbitmq.constants.Constant;
import com.example.java_chatroom_redis_rabbitmq.model.Result;
import com.example.java_chatroom_redis_rabbitmq.model.User;
import com.example.java_chatroom_redis_rabbitmq.service.UserService;
import com.example.java_chatroom_redis_rabbitmq.utils.RabbitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RabbitUtil rabbitUtil;
    @Transactional
    @RequestMapping("/registry")
    public Result<Boolean> registry(String userName, String password, String repassword, MultipartFile file) {
        log.info("【registry】userName:" + userName + ",password:" + password + ",repassword:" + repassword);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)
        || !StringUtils.hasLength(repassword) || file == null) {
            return Result.fail(400,false,"用户名、密码、确认密码或者上传的头像为空，请检查后重试!");
        }
        if (!password.equals(repassword)) {
            return Result.fail(400,false,"两次输入的密码不相同，请检查后重试!");
        }
        User queryUser = userService.queryUserByUserName(userName);
        if (queryUser != null) {
            return Result.fail(400,false,"该用户已存在!");
        }
        //判断上传的文件是否为图像类型
        String type = file.getContentType();
        String fileName = file.getOriginalFilename();
        for (String s : Constant.imageType) {
            if (type.equals(s)) {
                String suffix = fileName.substring(fileName.lastIndexOf('.'));
                userService.addUser(userName,password,userName + suffix,"normal");
                try {
                    file.transferTo(new File(Constant.path + userName + suffix));
                } catch (IOException e) {
                    log.error("文件存储失败");
                    return Result.fail(500,false,"文件上传失败，请联系管理员");
                }
                //用户注册之后为用户创建一个交换机并且绑定消息队列
                rabbitUtil.createExchange(userName);
                return Result.success(true);
            }
        }
        return Result.fail(400,false,"您上传的文件类型非图像类型!");
    }

    @RequestMapping("/login")
    public Result<Boolean> login(String userName, String password, HttpServletRequest request) {
        log.info("【login】userName:" + userName + ",password:" + password);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail(400,false,"用户名或者密码为空!");
        }
        User user = userService.queryUserByUserName(userName);
        if (user == null || user.getUserId() < 0) {
            return Result.fail(400,false,"该用户不存在");
        }
        if (password.equals(user.getPassword())) {
            HttpSession session = request.getSession(true);
            user.setPassword("");
            session.setAttribute("user",user);
            return Result.success(true);
        }
        return Result.fail(400,false,"用户名或者密码错误!");
    }

    @RequestMapping("/getUserInfo")
    public Result<User> getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        return Result.success(user);
    }

    @RequestMapping("/getPic")
    public ResponseEntity<Resource> getPic(String fileName) {
        log.info("fileName:" + fileName);
        Resource resource = new FileSystemResource(Constant.path + fileName);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .header(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=" + resource.getFilename())
                .body(resource);
    }

    @PostMapping("/getUserInfoByUserName")
    public Result<User> getUserInfoByUserName(String userName) {
        User user = userService.queryUserByUserName(userName);
        return Result.success(user);
    }
}
